package com.lsl.mydrawingboarddemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;

import com.lsl.mydrawingboarddemo.util.ScreenshotActivity;
import com.lsl.mydrawingboarddemo.view.DrawingBoardView;

import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * author lishilin
 * date 2023/8/9
 * desc 负责画板UI交互
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageButton paintBtn,fillPaintBtn,rubberBtn,rectBtn,circleBtn,ellipticBtn,triangleBtn,triangleTowerBtn,selectedBtn,clearBtn,equilateralBtn,rightAngleBtn,cameraBtn;
    private ImageButton blackBtn,whiteBtn,redBtn,blueBtn,grayBtn,cyanBtn,currentColorBtn;
    private DrawingBoardView drawingBoardView;
    private View selectColorBoxView;
    MediaProjectionManager mediaProjectionManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView(){
        paintBtn = findViewById(R.id.paint);
        fillPaintBtn = findViewById(R.id.fillPaint);
        //rubberBtn = findViewById(R.id.rubber);
        rectBtn = findViewById(R.id.rect);
        cameraBtn = findViewById(R.id.screenshot);
        circleBtn = findViewById(R.id.circle);
        ellipticBtn = findViewById(R.id.elliptic);
        triangleBtn = findViewById(R.id.triangle);
        triangleTowerBtn = findViewById(R.id.triangleTower);
        clearBtn = findViewById(R.id.clear);
        equilateralBtn = findViewById(R.id.equilateralTriangle);
        drawingBoardView = findViewById(R.id.drawView);
        selectColorBoxView = findViewById(R.id.selectColorBox);
        rightAngleBtn = findViewById(R.id.rightAngle);

        blackBtn = findViewById(R.id.blackBtn);
        whiteBtn = findViewById(R.id.whiteBtn);
        redBtn = findViewById(R.id.redBtn);
        blueBtn = findViewById(R.id.blueBtn);
        grayBtn = findViewById(R.id.grayBtn);
        cyanBtn = findViewById(R.id.cyanBtn);

        paintBtn.setSelected(true);
        selectedBtn = paintBtn;
        blackBtn.setSelected(true);
        currentColorBtn = blackBtn;

        paintBtn.setOnClickListener(this);
        fillPaintBtn.setOnClickListener(this);
        //rubberBtn.setOnClickListener(this);
        rectBtn.setOnClickListener(this);
        circleBtn.setOnClickListener(this);
        ellipticBtn.setOnClickListener(this);
        triangleBtn.setOnClickListener(this);
        triangleTowerBtn.setOnClickListener(this);
        clearBtn.setOnClickListener(this);
        blackBtn.setOnClickListener(this);
        whiteBtn.setOnClickListener(this);
        redBtn.setOnClickListener(this);
        blueBtn.setOnClickListener(this);
        grayBtn.setOnClickListener(this);
        equilateralBtn.setOnClickListener(this);
        rightAngleBtn.setOnClickListener(this);
        cyanBtn.setOnClickListener(this);
        cameraBtn.setOnClickListener(this);

        mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.paint:
                setSelectBtn(paintBtn);
                drawingBoardView.setPaint("paint");
                selectColorBoxView.setVisibility(View.VISIBLE);
                break;
            case R.id.fillPaint:
                setSelectBtn(fillPaintBtn);
                drawingBoardView.setPaint("fillPaint");
                selectColorBoxView.setVisibility(View.VISIBLE);
                break;
//            case R.id.rubber:
//                setSelectBtn(rubberBtn);
//                drawingBoardView.setEraseMode();
//                selectColorBoxView.setVisibility(View.INVISIBLE);
//                break;
            case R.id.rect:
                setSelectBtn(rectBtn);
                selectColorBoxView.setVisibility(View.VISIBLE);
                drawingBoardView.setPaint("rect");
                break;
            case R.id.circle:
                setSelectBtn(circleBtn);
                selectColorBoxView.setVisibility(View.VISIBLE);
                drawingBoardView.setPaint("drawCircle");
                break;
            case R.id.elliptic:
                setSelectBtn(ellipticBtn);
                selectColorBoxView.setVisibility(View.VISIBLE);
                drawingBoardView.setPaint("drawOval");
                break;
            case R.id.triangle:
                 setSelectBtn(triangleBtn);
                selectColorBoxView.setVisibility(View.VISIBLE);
                 drawingBoardView.setPaint("drawTriangle");
                 break;
            case R.id.equilateralTriangle:
                setSelectBtn(equilateralBtn);
                selectColorBoxView.setVisibility(View.VISIBLE);
                drawingBoardView.setPaint("drawEquilateral");
                break;
            case R.id.triangleTower:
                setSelectBtn(triangleTowerBtn);
                selectColorBoxView.setVisibility(View.VISIBLE);
                drawingBoardView.setPaint("drawTriangleTower");
                break;
            case R.id.rightAngle:
                setSelectBtn(rightAngleBtn);
                selectColorBoxView.setVisibility(View.VISIBLE);
                drawingBoardView.setPaint("drawRightAngle");
                break;
            case R.id.clear:
                clearStyle();//设置点击清除图标时的背景闪烁
                selectColorBoxView.setVisibility(View.VISIBLE);
                if (drawingBoardView!=null){
                    drawingBoardView.clearBoard();
                }
                break;
            case R.id.screenshot:
                Intent intent = new Intent(this, ScreenshotActivity.class);
                //startActivity(intent);
                break;
            case R.id.blackBtn:
                int blackColor = ContextCompat.getColor(this,R.color.black);
                drawingBoardView.setPaintColor(blackColor);
                setCurrentColorBtn(blackBtn);
                break;
            case R.id.blueBtn:
                int blueColor = ContextCompat.getColor(this,R.color.blue);
                drawingBoardView.setPaintColor(blueColor);
                setCurrentColorBtn(blueBtn);
                break;
            case R.id.whiteBtn:
                int whiteColor = ContextCompat.getColor(this,R.color.white);
                drawingBoardView.setPaintColor(whiteColor);
                setCurrentColorBtn(whiteBtn);
                break;
            case R.id.cyanBtn:
                int cyanColor = ContextCompat.getColor(this,R.color.cyan);
                drawingBoardView.setPaintColor(cyanColor);
                setCurrentColorBtn(cyanBtn);
                break;
            case R.id.grayBtn:
                int grayColor = ContextCompat.getColor(this,R.color.gray);
                drawingBoardView.setPaintColor(grayColor);
                setCurrentColorBtn(grayBtn);
                break;
            case R.id.redBtn:
                int redColor = ContextCompat.getColor(this,R.color.red);
                drawingBoardView.setPaintColor(redColor);
                setCurrentColorBtn(redBtn);
                break;
        }
    }

    /**
     * 设置选中的图形button
     * @param selectBtn
     */
    private void setSelectBtn(ImageButton selectBtn){
        if (this.selectedBtn!=null){
            this.selectedBtn.setSelected(false);
        }
        selectBtn.setSelected(true);
        this.selectedBtn = selectBtn;
    }

    private void setCurrentColorBtn(ImageButton currentColorBtn){
        if (this.currentColorBtn!=null){
            this.currentColorBtn.setSelected(false);
        }
        currentColorBtn.setSelected(true);
        this.currentColorBtn = currentColorBtn;
    }
    /**
     * 设置点击清除图标时的样式变化，让其背景变色500毫秒
     */
    private void clearStyle(){
        clearBtn.setSelected(true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                clearBtn.setSelected(false);
            }
        }, 200);
    }

    private static final int REQUEST_CODE = 999;
    private void screenshot() {
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.MEDIA_CONTENT_CONTROL) != PackageManager.PERMISSION_GRANTED
        || ContextCompat.checkSelfPermission(this,Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
            Intent permissionIntent = mediaProjectionManager.createScreenCaptureIntent();
            startActivityForResult(permissionIntent, REQUEST_CODE);
        }else{

        }

    }

    @Override
    public void onActivityResult(int requestCode,int resultCode,Intent intent) {

        super.onActivityResult(requestCode, resultCode, intent);
        if(REQUEST_CODE == requestCode){
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED){
                MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, intent);
                DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
                Display display = getWindowManager().getDefaultDisplay();
                int screenDensity = displayMetrics.densityDpi;
                WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                windowManager.getDefaultDisplay().getMetrics(displayMetrics);

                int screenWidth = displayMetrics.widthPixels;
                int screenHeight = displayMetrics.heightPixels;
                @SuppressLint("WrongConstant")
                ImageReader imageReader = ImageReader.newInstance(screenWidth, screenHeight, PixelFormat.RGBA_8888, 2);
                VirtualDisplay virtualDisplay = mediaProjection.createVirtualDisplay(
                        "ScreenCapture",
                        screenWidth,
                        screenHeight,
                        screenDensity,
                        DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                        imageReader.getSurface(),
                        null,
                        null
                );
                imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
                    @Override
                    public void onImageAvailable(ImageReader reader) {
                        Image image = reader.acquireLatestImage();
                        // 处理截图图像数据
                        if (image != null) {

                            image.close();
                        }
                    }
                }, null);
            }
        }
    }
    private void doScreenshot(){

    }
}